<template>
  <div class="flex gap-2">
    <button
      v-if="buttons.includes('first')"
      class="btn btn-circle"
      :disabled="isFirstPage"
      @click="currentPage = 1"
    >
      <span class="icon-[mdi--page-first] h-5 w-5" />
    </button>
    <button
      v-if="buttons.includes('previous')"
      class="btn btn-circle"
      :disabled="isFirstPage"
      @click="currentPage--"
    >
      <span class="icon-[mdi--arrow-left] h-5 w-5" />
    </button>
    <button
      class="btn btn-circle"
      :class="{ 'btn-primary btn-active': p == currentPage }"
      v-for="p in pageCount"
      :key="p"
      @click="currentPage = p"
    >
      {{ p }}
    </button>
    <button
      v-if="buttons.includes('next')"
      class="btn btn-circle"
      :disabled="isLastPage"
      @click="currentPage++"
    >
      <span class="icon-[mdi--arrow-right] h-5 w-5" />
    </button>
    <button
      v-if="buttons.includes('last')"
      class="btn btn-circle"
      :disabled="isLastPage"
      @click="currentPage = pageCount"
    >
      <span class="icon-[mdi--page-last] h-6 w-6"></span>
    </button>
    <select
      class="select"
      v-if="sizeOptions"
      v-model="currentPageSize"
      :options="sizeOptions"
    ></select>
  </div>
</template>
<script setup lang="ts">
import { watch, toRefs } from "vue";
import { useOffsetPagination } from "@vueuse/core";

type ButtonType = "first" | "previous" | "next" | "last";

interface Props {
  total: number;
  page?: number;
  pageSize?: number;
  buttons?: ButtonType[];
  sizeOptions?: number[];
}
const props = withDefaults(defineProps<Props>(), {
  page: 1,
  pageSize: 10,
  buttons: () => [],
});

// 定义事件
const emit = defineEmits<{
  "update:page": [val: number];
  "update:pageSize": [val: number];
}>();

const { total, page, pageSize } = toRefs(props);

// 分页
const { currentPage, currentPageSize, pageCount, isFirstPage, isLastPage } =
  useOffsetPagination({
    total,
    page: props.page,
    pageSize: props.pageSize,
  });

watch(currentPage, (val) => emit("update:page", val));
watch(page, (val) => (currentPage.value = val));
watch(currentPageSize, (val) => emit("update:pageSize", val));
watch(pageSize, (val) => (currentPageSize.value = val));
</script>
